console.log("Testing all frontend APIs...");
const http = require('http');

const testUrls = [
    { path: '/api/v1/index/search', name: '接口1: 文章搜索' },
    { path: '/api/v1/index/category', name: '接口2: 文章类型' }, 
    { path: '/api/v1/index/hotpic', name: '接口3: 热点图片' },
    { path: '/api/v1/index/rank', name: '接口4: 文章热门排行' },
    { path: '/api/v1/index/latest', name: '接口5: 最新资讯' },
    { path: '/api/v1/index/latest_comment', name: '接口6: 最新评论' },
    { path: '/api/v1/index/attention', name: '接口7: 焦点关注' },
    { path: '/api/v1/index/article?id=127', name: '接口8: 文章详细内容' }
];

async function testInterface(url, name) {
    return new Promise((resolve, reject) => {
        const options = {
            hostname: 'localhost',
            port: 8000,
            path: url,
            method: 'GET'
        };

        const req = http.request(options, (res) => {
            let data = '';
            res.on('data', (chunk) => {
                data += chunk;
            });
            res.on('end', () => {
                try {
                    const jsonData = JSON.parse(data);
                    resolve({ name, path: url, status: res.statusCode, data: jsonData });
                } catch (e) {
                    resolve({ name, path: url, status: res.statusCode, data: data });
                }
            });
        });

        req.on('error', (e) => {
            reject({ name, path: url, error: e.message });
        });

        req.setTimeout(5000, () => {
            req.destroy();
            reject({ name, path: url, error: 'Timeout' });
        });

        req.end();
    });
}

async function runTests() {
    console.log('开始测试所有前端接口...\n');
    
    for (const urlInfo of testUrls) {
        try {
            const result = await testInterface(urlInfo.path, urlInfo.name);
            console.log(`✓ ${result.name}`);
            console.log(`  URL: ${result.path}`);
            console.log(`  Status: ${result.status}`);
            if (result.data && typeof result.data === 'object') {
                console.log(`  Response fields: ${Object.keys(result.data).join(', ')}`);
                if (result.data.data && Array.isArray(result.data.data)) {
                    console.log(`  Data count: ${result.data.data.length}`);
                    if (result.data.data.length > 0) {
                        console.log(`  Sample fields: ${Object.keys(result.data.data[0]).join(', ')}`);
                    }
                }
            }
        } catch (error) {
            console.log(`✗ ${error.name}`);
            console.log(`  URL: ${error.path}`);
            console.log(`  Error: ${error.error}`);
        }
        console.log('');
    }
    
    process.exit(0);
}

runTests().catch(console.error);
